package com.mapproject.industrymap.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import de.odysseus.staxon.json.JsonXMLConfig;
import de.odysseus.staxon.json.JsonXMLConfigBuilder;
import de.odysseus.staxon.json.JsonXMLInputFactory;
import de.odysseus.staxon.json.JsonXMLOutputFactory;
import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class XmlConverUtil {
//    public static void main(String[] args) throws Exception {
//        String xmlStr = readFile("D:/xmltest/控制性详细规划.sld");
////        String jsonStr = readFile("D:/xmltest/jsonStr.json");
//        //System.out.println(XmlToJson(xmlStr));
//        String ret=XmlToJson(xmlStr);
//      ret=  ret.replaceAll("se:","");
//        ret=  ret.replaceAll("ogc:","");
//        System.out.println(JSON.parse(ret));
//    }
    public    String jsonKeyMark="n";
    public  JSONObject result=new JSONObject();
    public  String XmlToJson(String xmlString) {

        StringReader input = new StringReader(xmlString);
        StringWriter output = new StringWriter();
        JsonXMLConfig config = new JsonXMLConfigBuilder()
                .autoArray(true)
                .autoPrimitive(true)
                .prettyPrint(true)
                .namespaceDeclarations(true)
                .build();
        try {
            XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);
            XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
            writer.add(reader);
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return output.toString();
    }

    /**
     * @Description: json convert to xml
     * @author xxxg
     */
    public  String JsonToXml(String jsonString) {
        StringReader input = new StringReader(jsonString);
        StringWriter output = new StringWriter();
        JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
        try {
            XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
            XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
            writer = new PrettyXMLEventWriter(writer);
            writer.add(reader);
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // remove <?xml version="1.0" encoding="UTF-8"?>
        if (output.toString().length() >= 38) {
            return output.toString().substring(39);
        }
        return output.toString();
    }

    /**
     * @Description: 去掉xml中的换行和空格
     * @author @author xxxg
     */
    public  String JsonToXmlReplaceBlank(String jsonString) {
        String str =JsonToXml(jsonString);
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    public  String readFile(String path) throws Exception {
        File file = new File(path);
        FileInputStream fis = new FileInputStream(file);
        FileChannel fc = fis.getChannel();
        ByteBuffer bb = ByteBuffer.allocate(new Long(file.length()).intValue());
        //fc向buffer中读入数据
        fc.read(bb);
        bb.flip();
        String str = new String(bb.array(), "UTF8");
        fc.close();
        fis.close();
        return str;

    }
    public  JSONObject jsonLoop(Object object) {

        if(object instanceof JSONObject) {
            if(jsonKeyMark.equals("Rule")){
                JSONObject jsonObject=(JSONObject) object;
                String name= jsonObject.get("Name").toString();
                if(name.indexOf(".")==-1){
                    try {
                        String colorRet= colorLoop(jsonObject.get("PolygonSymbolizer"));
                        result.put(name,colorRet);
                    }catch (Exception e){
                    }

                }
            }
            JSONObject jsonObject = (JSONObject) object;
            for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
                Object o = entry.getValue();
                jsonKeyMark=entry.getKey();
                if(o instanceof String) {
                    System.out.println("key:" + entry.getKey() + "，value:" + entry.getValue());
                } else {
                      jsonLoop(o);
                }
            }
        }
        if(object instanceof JSONArray ) {
            if(jsonKeyMark.equals("Rule")){
                JSONArray jsonArray = (JSONArray) object;
                int arryLength=1;
                if(jsonArray.size()>1){
                    arryLength=jsonArray.size()-1;
                }
                for(int i = 0; i < arryLength; i ++) {
                JSONObject jsonObject=(JSONObject) jsonArray.get(i);
                    String name= jsonObject.get("Name").toString();
                if(name.indexOf(".")==-1){
                    try {
                        String colorRet= colorLoop(jsonObject.get("PolygonSymbolizer"));
                        result.put(name,colorRet);
                    }catch (Exception e){
                        result.put(name,"#cccccc");
                       continue;
                    }

                }
                }
            }
        }

        return result;
    }
    public  String colorLoop(Object object){
        JSONObject jsonObject = (JSONObject) object;
        JSONObject jsonObject2=(JSONObject) jsonObject.get("Fill");
        JSONObject jsonObject3=(JSONObject) jsonObject2.get("SvgParameter");
        String lastString=jsonObject3.get("$").toString();
        return lastString;
    }
}
